<?php

namespace common\models\project;

use common\enums\StatusEnum;
use common\helpers\ArrayHelper;
use common\models\common\Provinces;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "hxdc_project_region".
 *
 * @property int $id
 * @property int $merchant_id 商户id
 * @property int $top_id
 * @property string $title 区域名
 * @property int $updated_at 更新时间
 * @property string $country 国家
 * @property int $province_id 省
 * @property int $city_id 市
 * @property int $area_id 区
 * @property int $level 等级
 * @property int $status 状态0,1
 * @property int $created_at 创建时间时间戳
 */
class ProjectRegion extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'hxdc_project_region';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['created_at'], 'safe'],
            [['top_id', 'merchant_id', 'province_id', 'city_id', 'area_id', 'level', 'status', 'updated_at', 'created_at'], 'integer'],
            [['country'], 'required'],
            [['title'], 'string', 'max' => 30],
            [['address_name'], 'string', 'max' => 127],
            [['country'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'level' => '等级',
            'top_id' => '上级id',
            'title' => '区域名称',
            'updated_at' => '更新时间',
            'merchant_id' => '商户id',
            'country' => '国家',
            'province_id' => '省',
            'city_id' => '市',
            'area_id' => '区',
            'address_name' => '地址',
            'status' => '状态',
            'created_at' => '创建时间',
        ];
    }

    /**
     * 地区名关联
     *
     * @return \yii\db\ActiveQuery
     */
    public function regionname(){

        return $this->hasMany(Provinces::className(), ['province_id' => 'id']);
    }

    /**
     * 项目关联
     *
     * @return \yii\db\ActiveQuery
     */
    public function getProjects()
    {
        return $this->hasMany(Project::className(), ['region_id' => 'id']);
    }

    /**
     * 地区、头图关联表关联
     *
     * @return \yii\db\ActiveQuery
     */
    public function getLunboRegion()
    {
        return $this->hasMany(RegionToLunbo::class,['region_id' => 'id']);
    }

    /**
     * @param bool $insert
     * @return bool
     * @throws \yii\base\Exception
     */
    public function beforeSave($insert)
    {
        $this->address_name = Yii::$app->services->provinces->getCityListName([$this->province_id, $this->city_id, $this->area_id]);
        if ($this->isNewRecord) {
            $this->created_at = time();
        }

        // 处理上下级关系
//        $this->autoUpdateTree();
        return parent::beforeSave($insert);
    }


    /**
     * @return array
     */
    public function behaviors()
    {
        $merchant_id = Yii::$app->services->merchant->getId();
        return [
            [
                'class' => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
            [
                'class' => BlameableBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['merchant_id'],
                ],
                'value' => !empty($merchant_id) ? $merchant_id : 0,
            ]
        ];
    }



    /**
     * 获取树状数据
     *
     * @return mixed
     */
    public static function getTree()
    {
        $cates = self::find()
            ->where(['status' => StatusEnum::ENABLED])
            ->andWhere(['merchant_id' => Yii::$app->services->merchant->getId()])
            ->asArray()
            ->all();

        return ArrayHelper::itemsMerge($cates);
    }

    /**
     * 获取下拉
     *
     * @param string $id
     * @return array
     */
    public static function getDropDownForEdit($id = '')
    {
        $list = self::find()
            ->where(['>=', 'status', StatusEnum::DISABLED])
            ->andWhere(['merchant_id' => Yii::$app->services->merchant->getId()])
            ->andWhere(['<','level','3'])
            ->andFilterWhere(['<>', 'id', $id])
            ->select(['id', 'title', 'top_id', 'level'])
            ->orderBy('id asc')
            ->asArray()
            ->all();

        $models = ArrayHelper::itemsMerge($list);
        $data = ArrayHelper::map(ArrayHelper::itemsMergeDropDown($models), 'id', 'title');
        return ArrayHelper::merge([0 => '顶级分类'], $data);
    }

    /**
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getDropDown()
    {
        $models = ProjectRegion::find()
            ->where(['status' => StatusEnum::ENABLED])
            ->andWhere(['merchant_id' => Yii::$app->services->merchant->getId()])
            ->orderBy('id asc,created_at asc')
            ->asArray()
            ->all();

        $models = ArrayHelper::itemsMerge($models);
        return ArrayHelper::map(ArrayHelper::itemsMergeDropDown($models), 'id', 'title');
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getParent()
    {
        return $this->hasOne(self::class, ['id' => 'top_id']);
    }
}
